#!/bin/bash

# $1 is which disk to operate
# $2 to $n represent the partition's size(G), and the disk 
# will have how many parts.
function FDISK() 
{
	DISKNAME="/dev/$1"
	ROOTDISK=`mount |head -1|cut -b 1-8`
	if [ ! -e "$DISKNAME" -o "$DISKNAME" = "$ROOTDISK" ]; then
		echo "disk not exit or the disk is used by /"
		return 1
	fi

	# erase all the partition
	echo -ne "d\n1\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1
	echo -ne "d\n2\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1
	echo -ne "d\n3\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1
	echo -ne "d\n4\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1

	PARTS=1
	while [ $# -gt "1" ]; do
		shift
		if [ $PARTS -lt "4" ]; then
			echo -ne "n\np\n${PARTS}\n\n+$1G\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1
		elif [ $PARTS -eq "4" ]; then
			echo -ne "n\ne\n\n\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1
			((PARTS++))
			echo -ne "n\nl\n${PARTS}\n\n+$1G\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1
		else
			echo -ne "n\nl\n${PARTS}\n\n+$1G\nw\n" | fdisk $DISKNAME >/dev/NULL 2>&1
		fi
		((PARTS++))
	done

	partx $DISKNAME
	FSPARTS=`fdisk -l|grep $DISKNAME |awk '{if($5 == 83){print $1}}'`
	for i in $FSPARTS
	do
		mkfs.ext4 $i
	done
}

# calculate the average size for partition, the $1 is the num that disk will be parted
function CALPART()
{
	echo
}

FDISK sdd 1 2 1 1 1 1

